package com.qf.first.config;

import com.qf.first.base.untils.ShiroUtils;
import com.qf.first.realm.UserRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    /* *不加密认证
     * 注册自定义UserRealm
     * @return*/
/*    @Bean
    @Primary
    public UserRealm realm(){
        return new UserRealm();
    }*/
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        //散列算法   MD5
        // hashedCredentialsMatcher.setHashAlgorithmName(Md5Hash.ALGORITHM_NAME);
        //散列散发  sha256算法
        hashedCredentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);
        //设置加密次数
        hashedCredentialsMatcher.setHashIterations(ShiroUtils.HASH_ITERATIONS);
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        return hashedCredentialsMatcher;
    }
    /* 加密认证
     * 自定义注册realm
     * */
    @Bean
    public UserRealm realm(){
        UserRealm userRealm = new UserRealm();
        userRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userRealm;
    }
    /*
     * 配置securityManager
     */
    @Bean
    public DefaultWebSecurityManager securityManager(@Qualifier("realm") UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }
    /*    *
     * 权限，默认情况下所有的请求都要做认证
     * 开放不需要认证的url*/
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
        //不需要认证的写在前面,支持通配符
        defaultShiroFilterChainDefinition.addPathDefinition("/test/**", "anon");
        defaultShiroFilterChainDefinition.addPathDefinition("/user/login","anon");
        defaultShiroFilterChainDefinition.addPathDefinition("/druid/**", "anon");
        defaultShiroFilterChainDefinition.addPathDefinition("/user/register", "anon");
        //需要认证的写在后面
        defaultShiroFilterChainDefinition.addPathDefinition("/**","authc");
        return defaultShiroFilterChainDefinition;
    }
}
